//
//  JCLOAuthViewController.swift
//  WeiBo
//
//  Created by DDC on 2017/9/12.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import SVProgressHUD
class JCLOAuthViewController: UIViewController {

    
    //懒加载
    fileprivate lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
       
        //防止授权界面滚动
        webView.scrollView.isScrollEnabled = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "微博授权登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, taret: self, action: #selector(back))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, taret: self, action: #selector(autoFill))
        //webView代理
        webView.delegate = self 
        loadWebView()
    }
    @objc fileprivate func back () {
        
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    @objc fileprivate func autoFill () {
        
        //自动填充js代码
        let js = "document.getElementById('userId').value = 'jimmychenliang@sina.com' ;" + "document.getElementById('passwd').value = 'j15607103133' ;"
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    
    fileprivate func loadWebView () {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JCLAppID)&redirect_uri=\(JCLRedirectURI)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url) 
        
        webView.loadRequest(request)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}


// MARK: - UIWebViewDelegate
/*
 关于UIWebView中url的属性
 scheme --协议名称
 host   --协议头
 pathContent--数组
 query --?后面的所有内容
 */
extension JCLOAuthViewController :UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("将要读取---"+(request.url?.absoluteString)!)
        
        if request.url?.absoluteString.hasPrefix(JCLRedirectURI) == false {

            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            back()
            return false
        }
        
        //获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码---\(code)")
        JCLNetWorkTools.shared.loadAccessToken(code: code){ (isSuccess) in

            if isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                // 1.发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: JCLUserOAuthSuccessedNotificaton), object: nil)
                // 2.关闭授权界面
                self.back()
            
                
            }else {
                SVProgressHUD.showError(withStatus: "网络授权失败")
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
